package me.shurufa.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.bean.Excerpt;
import me.shurufa.fragments.ModifyMyDigestFragment;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestParams;
import me.shurufa.net.RequestServerTask;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘添加笔记界面
 */
public class ModifyMyDigestActivity extends BaseActivity implements View.OnClickListener {


    @Bind(R.id.left_text)
    TextView leftText;

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.toolbar_title)
    TextView toolbar_title;

    private Excerpt mExcerpt;
    private ModifyMyDigestFragment modifyMyDigestFragment;
    private int mPosition;
    private String mBookName;
    private long mBookId;
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_digest_add_note;
        super.onCreate(savedInstanceState);
        parseArguments();
        initUI();
    }

    /**
     * 传参
     * @param in
     * @param excerpt
     */
    public static void initArguments(Intent in, String bookName, long bookId, int position, Excerpt excerpt) {
        in.putExtra(Constants.ARG_MODIFY_DIGEST, excerpt);
        in.putExtra(Constants.ARG_MODIFY_POSITION, position);
        in.putExtra(Constants.ARG_BOOK_TITLE, bookName);
        in.putExtra(Constants.ARG_BOOK_ID, bookId);
    }

    /**
     * 解析参数
     */
    private void parseArguments() {
        mExcerpt = (Excerpt) getIntent().getSerializableExtra(Constants.ARG_MODIFY_DIGEST);
        mPosition = getIntent().getIntExtra(Constants.ARG_MODIFY_POSITION, -1);
        mBookName = getIntent().getStringExtra(Constants.ARG_BOOK_TITLE);
        mBookId = getIntent().getLongExtra(Constants.ARG_BOOK_ID, 0);
    }


    private void initUI() {
        titleTextView.setText(R.string.modify_my_digest);
        rightText.setText(getString(R.string.complete));
        rightText.setVisibility(View.VISIBLE);
        rightText.setOnClickListener(this);

        initFragment();
    }

    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        modifyMyDigestFragment = ModifyMyDigestFragment.newInstance(mBookName, mBookId, mExcerpt);
        ft.replace(R.id.fragment_container, modifyMyDigestFragment);
        ft.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                if (checkData()) {
                    reqEditExcerpt();
                }
                break;
        }
    }

    private void reqEditExcerpt() {
        final String content = mExcerpt.content;
        final String bookId = String.valueOf(mBookId);
        final String pageNumber = String.valueOf(mExcerpt.page_num);
        final String note = mExcerpt.note;
        final String publishState = mExcerpt.publish_state;
        final String notebookId = String.valueOf(modifyMyDigestFragment.getNoteBookId());
        final String menuId = String.valueOf(mExcerpt.menu_id);
        final String screenShot = mExcerpt.screenshot;
        final int type = mExcerpt.type;

        RequestParams params = new RequestParams();
        params.addFormDataPart("id", String.valueOf(mExcerpt.id));
        params.addFormDataPart("content", content == null ? "" : content);
        params.addFormDataPart("book_id", bookId);
        params.addFormDataPart("page_num", pageNumber);
        params.addFormDataPart("note", note);
        params.addFormDataPart("publish_state", publishState);
        params.addFormDataPart("screen_shot", screenShot == null ? "" : screenShot);
        params.addFormDataPart("menu_id", menuId);
        params.addFormDataPart("type", type);
        //params.addFormDataPart("notebook_id", notebookId);

        HttpRequest.post(API.EDIT_EXCERPT, params, new HttpCallback<BaseResp>() {
            @Override
            public void onRespSuccess(BaseResp resp) {
                try {
                    Utils.showToast("编辑成功");
                    Intent in = new Intent(Constants.EVENT_MODIFY_BOOK_DIGEST);
                    in.putExtra(Constants.ARG_MODIFY_DIGEST, mExcerpt);
                    in.putExtra(Constants.ARG_MODIFY_POSITION, mPosition);
                    EventBus.getDefault().post(in);

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 200);
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }
        });

    }

    /**
     * 请求修改书摘
     */
    private void reqModifyMyDigest() {
        final String content = mExcerpt.content;
        final String bookId = String.valueOf(mBookId);
        final String pageNumber = String.valueOf(mExcerpt.page_num);
        final String note = mExcerpt.note;
        final String publishState = mExcerpt.publish_state;
        final String notebookId = String.valueOf(modifyMyDigestFragment.getNoteBookId());
        final String menuId = String.valueOf(mExcerpt.menu_id);
        final String screenShot = mExcerpt.screenshot;
        final int type = mExcerpt.type;

        if ((!TextUtils.isEmpty(content) && content.length() > 6) || !TextUtils.isEmpty(screenShot)) {
            new RequestServerTask<BaseResponse>(BaseResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("excerptId", String.valueOf(mExcerpt.id));
                    params.put("content", content == null ? "" : content);
                    params.put("bookId", bookId);
                    params.put("pageNumber", pageNumber);
                    params.put("note", note);
                    params.put("publishState", publishState);
                    params.put("notebookId", notebookId);
                    params.put("screenShot", screenShot == null ? "" : screenShot);
                    params.put("menuId", menuId);
                    params.put("type", type);
                    return HttpUtil.post(API.MODIFY_DIGEST, params);
                }

                @Override
                protected void onSuccess(BaseResponse result) {
                    Utils.showToast("修改成功");

                    Intent in = new Intent(Constants.EVENT_MODIFY_BOOK_DIGEST);
                    in.putExtra(Constants.ARG_MODIFY_DIGEST, mExcerpt);
                    in.putExtra(Constants.ARG_MODIFY_POSITION, mPosition);
                    EventBus.getDefault().post(in);

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 200);

                }
            }.start();
        } else if (TextUtils.isEmpty(content)) {
            Utils.showToast(R.string.content_is_empty);
        } else {
            Utils.showToast(R.string.content_must_greater_than_6);
        }
    }

    /**
     * 校验数据
     * @return
     */
    private boolean checkData() {
        mExcerpt = modifyMyDigestFragment.getExcerpt();
        if (TextUtils.isEmpty(mExcerpt.content) && TextUtils.isEmpty(mExcerpt.screenshot) ) {
            Utils.showToast(getString(R.string.write_book_digest));
            return false;
        }

        /*if (0 == modifyMyDigestFragment.getNoteBookId()) {
            Utils.showToast(getString(R.string.select_book_digest));
            return false;
        }*/

        // 若是文字书摘 则限制长度为10-500
        if (0 == mExcerpt.type) {
            if (!TextUtils.isEmpty(mExcerpt.content)) {
                if (mExcerpt.content.length() < 10) {
                    Utils.showToast("书摘内容不可少于10字");
                    return false;
                }
                if (mExcerpt.content.length() > 500) {
                    Utils.showToast("书摘内容不可超过500字");
                    return false;
                }
            } else {
                Utils.showToast("书摘内容不可少于10字");
                return false;
            }
        }

        // 笔记
        if (!TextUtils.isEmpty(mExcerpt.note)) {
            if (mExcerpt.note.length() < 10) {
                Utils.showToast("笔记内容不可少于10字");
                return false;
            }

            if (mExcerpt.note.length() > 3000) {
                Utils.showToast("笔记内容不可超过3000字");
                return false;
            }
        }

        return true;
    }

}
